// 通用工具函数和配置

// API基础配置
const API_BASE_URL = window.location.origin;
const API_PREFIX = '';

// 用户登录状态
let currentUser = null;
let authToken = localStorage.getItem('auth-token');

// 工具函数
const Utils = {
    // API请求封装
    async request(url, options = {}) {
        const config = {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                ...options.headers
            },
            ...options
        };

        // 添加认证token
        if (authToken) {
            config.headers.Authorization = `Bearer ${authToken}`;
        }

        try {
            const response = await fetch(API_BASE_URL + url, config);
            const data = await response.json();
            
            if (data.code === 200) {
                return data;
            } else {
                throw new Error(data.msg || '请求失败');
            }
        } catch (error) {
            console.error('API请求错误:', error);
            throw error;
        }
    },

    // GET请求
    async get(url, params = {}) {
        const queryString = new URLSearchParams(params).toString();
        const fullUrl = queryString ? `${url}?${queryString}` : url;
        return this.request(fullUrl);
    },

    // POST请求
    async post(url, data = {}) {
        return this.request(url, {
            method: 'POST',
            body: JSON.stringify(data)
        });
    },

    // PUT请求
    async put(url, data = {}) {
        return this.request(url, {
            method: 'PUT',
            body: JSON.stringify(data)
        });
    },

    // DELETE请求
    async delete(url) {
        return this.request(url, {
            method: 'DELETE'
        });
    },

    // 格式化日期
    formatDate(date, format = 'YYYY-MM-DD') {
        if (!date) return '';
        const d = new Date(date);
        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        const hour = String(d.getHours()).padStart(2, '0');
        const minute = String(d.getMinutes()).padStart(2, '0');
        const second = String(d.getSeconds()).padStart(2, '0');

        return format
            .replace('YYYY', year)
            .replace('MM', month)
            .replace('DD', day)
            .replace('HH', hour)
            .replace('mm', minute)
            .replace('ss', second);
    },

    // 显示消息提示
    showMessage(message, type = 'info') {
        const messageEl = document.createElement('div');
        messageEl.className = `message message-${type}`;
        messageEl.innerHTML = `
            <div class="message-content">
                <span class="message-text">${message}</span>
                <button class="message-close" onclick="this.parentElement.parentElement.remove()">&times;</button>
            </div>
        `;
        
        // 添加样式
        messageEl.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
            max-width: 400px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.15);
            border-left: 4px solid ${type === 'success' ? '#52c41a' : type === 'error' ? '#ff4d4f' : type === 'warning' ? '#faad14' : '#1890ff'};
            animation: slideInRight 0.3s ease;
        `;

        messageEl.querySelector('.message-content').style.cssText = `
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 16px;
            gap: 12px;
        `;

        messageEl.querySelector('.message-close').style.cssText = `
            background: none;
            border: none;
            font-size: 18px;
            cursor: pointer;
            color: #999;
            padding: 0;
            width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
        `;

        document.body.appendChild(messageEl);

        // 3秒后自动移除
        setTimeout(() => {
            if (messageEl.parentNode) {
                messageEl.remove();
            }
        }, 3000);
    },

    // 确认对话框
    confirm(message, title = '确认') {
        return new Promise((resolve) => {
            const modal = document.createElement('div');
            modal.className = 'modal';
            modal.style.display = 'block';
            modal.innerHTML = `
                <div class="modal-content" style="max-width: 400px;">
                    <h3 style="color: var(--medical-blue); margin-bottom: 16px;">${title}</h3>
                    <p style="margin-bottom: 24px; line-height: 1.5;">${message}</p>
                    <div style="display: flex; gap: 12px; justify-content: flex-end;">
                        <button class="btn-secondary" onclick="this.closest('.modal').remove(); window.confirmResult = false;">取消</button>
                        <button class="btn-primary" onclick="this.closest('.modal').remove(); window.confirmResult = true;">确定</button>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            
            // 监听点击事件
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    modal.remove();
                    resolve(false);
                }
            });
            
            // 轮询结果
            const checkResult = () => {
                if (window.confirmResult !== undefined) {
                    const result = window.confirmResult;
                    window.confirmResult = undefined;
                    resolve(result);
                } else if (document.contains(modal)) {
                    setTimeout(checkResult, 100);
                }
            };
            checkResult();
        });
    },

    // 防抖函数
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },

    // 节流函数
    throttle(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    },

    // 获取查询参数
    getQueryParam(name) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(name);
    },

    // 深拷贝
    deepClone(obj) {
        if (obj === null || typeof obj !== 'object') return obj;
        if (obj instanceof Date) return new Date(obj);
        if (obj instanceof Array) return obj.map(item => this.deepClone(item));
        if (typeof obj === 'object') {
            const clonedObj = {};
            for (const key in obj) {
                if (obj.hasOwnProperty(key)) {
                    clonedObj[key] = this.deepClone(obj[key]);
                }
            }
            return clonedObj;
        }
    }
};

// 登录相关功能
const Auth = {
    // 检查登录状态
    isLoggedIn() {
        return !!authToken && !!currentUser;
    },

    // 设置用户信息
    setUser(user, token) {
        currentUser = user;
        authToken = token;
        localStorage.setItem('auth-token', token);
        localStorage.setItem('current-user', JSON.stringify(user));
        this.updateNavbar();
    },

    // 清除用户信息
    clearUser() {
        currentUser = null;
        authToken = null;
        localStorage.removeItem('auth-token');
        localStorage.removeItem('current-user');
        this.updateNavbar();
    },

    // 从本地存储恢复用户信息
    restoreUser() {
        const token = localStorage.getItem('auth-token');
        const userStr = localStorage.getItem('current-user');
        
        if (token && userStr) {
            try {
                authToken = token;
                currentUser = JSON.parse(userStr);
                this.updateNavbar();
                return true;
            } catch (error) {
                console.error('恢复用户信息失败:', error);
                this.clearUser();
            }
        }
        return false;
    },

    // 更新导航栏显示
    updateNavbar() {
        const loginBtn = document.querySelector('.login-btn');
        const navAuth = document.querySelector('.nav-auth');
        
        if (!loginBtn || !navAuth) return;

        if (this.isLoggedIn()) {
            loginBtn.textContent = `欢迎, ${currentUser.nickName || currentUser.userName}`;
            loginBtn.onclick = () => this.logout();
        } else {
            loginBtn.textContent = '登录';
            loginBtn.onclick = () => showLoginModal();
        }
    },

    // 登录
    async login(username, password) {
        try {
            const response = await Utils.post('/login', {
                username,
                password,
                code: '1234', // 固定验证码或后端不验证
                uuid: 'hero-login'
            });
            
            if (response.code === 200) {
                const token = response.token || response.data?.token;
                console.log('登录响应:', response);
                console.log('获取到的token:', token);
                
                if (!token) {
                    throw new Error('未获取到token');
                }
                
                // 设置token到全局变量
                authToken = token;
                localStorage.setItem('auth-token', token);
                
                // 获取用户信息
                const userInfo = await Utils.get('/getInfo');
                if (userInfo.code === 200) {
                    this.setUser(userInfo.user, token);
                    Utils.showMessage('登录成功', 'success');
                    closeLoginModal();
                    
                    // 如果在申请页面，显示申请表单
                    if (window.location.pathname.includes('apply.html')) {
                        document.getElementById('loginRequired').style.display = 'none';
                        document.getElementById('applicationSection').style.display = 'block';
                    }
                    
                    return true;
                } else {
                    throw new Error('获取用户信息失败');
                }
            } else {
                throw new Error(response.msg || '登录失败');
            }
        } catch (error) {
            Utils.showMessage(error.message, 'error');
            return false;
        }
    },

    // 登出
    async logout() {
        const confirmed = await Utils.confirm('确定要退出登录吗？', '退出确认');
        if (confirmed) {
            this.clearUser();
            Utils.showMessage('已退出登录', 'info');
            
            // 如果在申请页面，隐藏申请表单
            if (window.location.pathname.includes('apply.html')) {
                document.getElementById('applicationSection').style.display = 'none';
                document.getElementById('loginRequired').style.display = 'block';
            }
        }
    }
};

// 分页组件
class Pagination {
    constructor(container, options = {}) {
        this.container = typeof container === 'string' ? document.querySelector(container) : container;
        this.options = {
            page: 1,
            size: 10,
            total: 0,
            showInfo: true,
            showJump: true,
            onChange: () => {},
            ...options
        };
        this.render();
    }

    render() {
        if (!this.container) return;

        const { page, size, total, showInfo, showJump } = this.options;
        const totalPages = Math.ceil(total / size);
        
        if (totalPages <= 1) {
            this.container.innerHTML = '';
            return;
        }

        let html = '<div class="pagination-wrapper">';
        
        // 分页信息
        if (showInfo) {
            const start = (page - 1) * size + 1;
            const end = Math.min(page * size, total);
            html += `<div class="pagination-info">共 ${total} 条，第 ${start}-${end} 条</div>`;
        }
        
        html += '<div class="pagination-controls">';
        
        // 上一页
        html += `<button ${page <= 1 ? 'disabled' : ''} onclick="this.pagination.goToPage(${page - 1})">上一页</button>`;
        
        // 页码
        const startPage = Math.max(1, page - 2);
        const endPage = Math.min(totalPages, page + 2);
        
        if (startPage > 1) {
            html += `<button onclick="this.pagination.goToPage(1)">1</button>`;
            if (startPage > 2) {
                html += '<span class="pagination-ellipsis">...</span>';
            }
        }
        
        for (let i = startPage; i <= endPage; i++) {
            html += `<button ${i === page ? 'class="active"' : ''} onclick="this.pagination.goToPage(${i})">${i}</button>`;
        }
        
        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                html += '<span class="pagination-ellipsis">...</span>';
            }
            html += `<button onclick="this.pagination.goToPage(${totalPages})">${totalPages}</button>`;
        }
        
        // 下一页
        html += `<button ${page >= totalPages ? 'disabled' : ''} onclick="this.pagination.goToPage(${page + 1})">下一页</button>`;
        
        html += '</div></div>';
        
        this.container.innerHTML = html;
        this.container.querySelector('.pagination-wrapper').pagination = this;
    }

    goToPage(newPage) {
        if (newPage < 1 || newPage > Math.ceil(this.options.total / this.options.size)) {
            return;
        }
        
        this.options.page = newPage;
        this.render();
        this.options.onChange(newPage);
    }

    update(options) {
        Object.assign(this.options, options);
        this.render();
    }
}

// 公共模态框函数
function showLoginModal() {
    const modal = document.getElementById('loginModal');
    if (modal) {
        modal.style.display = 'block';
    }
}

function closeLoginModal() {
    const modal = document.getElementById('loginModal');
    if (modal) {
        modal.style.display = 'none';
        // 重置表单
        const form = document.getElementById('loginForm');
        if (form) form.reset();
    }
}

function refreshCaptcha() {
    // 验证码功能已禁用
}

function goToAdmin() {
    // 检查是否已登录
    if (!Auth.isLoggedIn()) {
        Utils.showMessage('请先登录后再访问管理后台', 'warning');
        showLoginModal();
        return;
    }
    
    // 跳转到管理后台（Vue前端）
    window.open('http://localhost:80', '_blank');
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
    // 恢复用户登录状态
    Auth.restoreUser();
    
    // 登录表单提交
    const loginForm = document.getElementById('loginForm');
    if (loginForm) {
        loginForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const username = formData.get('username');
            const password = formData.get('password');
            
            await Auth.login(username, password);
        });
    }
    
    // 模态框点击外部关闭
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('modal')) {
            e.target.style.display = 'none';
        }
    });
});

// 添加CSS样式
const style = document.createElement('style');
style.textContent = `
    @keyframes slideInRight {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }

    .pagination-wrapper {
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 16px;
    }

    .pagination-info {
        color: var(--text-secondary);
        font-size: 14px;
    }

    .pagination-controls {
        display: flex;
        gap: 8px;
        align-items: center;
    }

    .pagination-ellipsis {
        padding: 8px;
        color: var(--text-disabled);
    }

    @media (max-width: 768px) {
        .pagination-wrapper {
            flex-direction: column;
            align-items: center;
        }
    }
`;
document.head.appendChild(style);

// 导出全局对象
window.Utils = Utils;
window.Auth = Auth;
window.Pagination = Pagination;